package com.winit.openapi.wh.allocation.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONObject;
import com.winit.common.query.Page;
import com.winit.common.query.Searchable;
import com.winit.common.query.Sort;
import com.winit.common.query.Sort.Direction;
import com.winit.common.spi.context.CommandContext;
import com.winit.oms.spi.allocation.service.order.AllocationOrderMerchandiseService;
import com.winit.oms.spi.allocation.vo.order.AllocationOrderMerchandiseVo;
import com.winit.oms.spi.inbound.InboundMerchandiseService;
import com.winit.oms.spi.inbound.command.QueryCrossDockActualItemQtyCommand;
import com.winit.oms.spi.inbound.command.QueryInboundMerchandiseCommand;
import com.winit.oms.spi.inbound.vo.InboundMerchandiseDetailsVo;
import com.winit.oms.spi.outbound.command.order.DeleteOrderMerchandiseCommand;
import com.winit.oms.spi.outbound.command.order.QueryOrderMerchandiseByOrderNoCommand;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.controller.BaseController;
import com.winit.openapi.exception.ApiException;
import com.winit.openapi.model.RequestMsg;
import com.winit.openapi.model.ResponseMsg;
import com.winit.openapi.util.ValidateUtil;
import com.winit.openapi.wh.allocation.builder.AllocationOrderMerchandiseBuilder;

@Controller
@RequestMapping(value = "/wh/allocation")
public class AllocationOrderMerchandiseController extends BaseController{

    @Resource
    private AllocationOrderMerchandiseService allocationOrderMerchandiseService;
    
    @Resource
    private InboundMerchandiseService         inboundMerchandiseService;
    
    @RequestMapping(value = "/getMerchandsieList")
    public String getMerchandsieList(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        QueryOrderMerchandiseByOrderNoCommand command = new QueryOrderMerchandiseByOrderNoCommand();
        Object obj = requestMsg.getData();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            ValidateUtil.validNotNull(json, "orderNo");
            ValidateUtil.validMaxLength(json, "orderNo", 64);
            command.setOrderNo(json.getString("orderNo"));
            Searchable searchable = buildSearchablePageParams(json);
            searchable.addSort(new Sort(Direction.DESC, "CREATED"));
            command.setSearchable(searchable);
        } else if (obj == null || StringUtils.isBlank(obj.toString())) {
            Searchable searchable = buildSearchablePageParams(null);
            command.setSearchable(searchable);
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        Page<AllocationOrderMerchandiseVo> pagelist = allocationOrderMerchandiseService.getMerchandiseListBySeller(command);
        if (pagelist != null && pagelist.getContent() != null && pagelist.getContent().size() > 0) {
            List<Map<String, Object>> datalist = AllocationOrderMerchandiseBuilder.buildMerchandiseList(pagelist.getContent());
            Map<String, Object> pageMap = getPageParams(pagelist);
            Map<String, Object> data = new HashMap<String, Object>();
            data.put("merchandiseInfoList", datalist);
            data.put("pageParams", pageMap.get("pageParams"));
            responseMsg.setData(data);
        }
        return SUCCESS;
    }
    
    @RequestMapping(value = "/queryMerchandiseList")
    public String queryMerchandiseList(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        QueryOrderMerchandiseByOrderNoCommand command = new QueryOrderMerchandiseByOrderNoCommand();
        Object obj = requestMsg.getData();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            ValidateUtil.validNotNull(json, "orderNo");
            ValidateUtil.validMaxLength(json, "orderNo", 64);
            command.setOrderNo(json.getString("orderNo"));
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        List<AllocationOrderMerchandiseVo> merlist = allocationOrderMerchandiseService.getMerchandiseList(command);
        if (merlist != null && merlist.size() > 0) {
            List<Map<String, Object>> datalist = AllocationOrderMerchandiseBuilder.buildMerchandiseList(merlist);
            Map<String, Object> data = new HashMap<String, Object>();
            data.put("merchandiseInfoList", datalist);
            responseMsg.setData(data);
        }
        return SUCCESS;
    }
    
    @RequestMapping(value="/deleteMerchandsie")
    public String  getDeleteMerchandsie(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg){
    	Object obj = requestMsg.getData();
    	DeleteOrderMerchandiseCommand command = new DeleteOrderMerchandiseCommand();
    	 if (obj instanceof JSONObject) {
             JSONObject json = (JSONObject) obj;
             ValidateUtil.validNotNull(json, "orderNo");
             ValidateUtil.validNotNull(json, "merchandiseId");
             command.setMerchandiseId(json.getLong("merchandiseId"));
         } else {
             throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
         }
         allocationOrderMerchandiseService.deleteMerchandiseId(command);
         responseMsg.setMsg("SUCCESS");
         return SUCCESS;
    	
    }
    
    /**
     * 查询越库商品列表
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/queryCrossDockMerchandises")
    public String queryCrossDockMerchandises(@ModelAttribute RequestMsg requestMsg,
                                           @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        String winitOrderNo = null;
        String allocationOrderNo = null;
        String isByRecommandQty = null;
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            ValidateUtil.validNotNull(json, "winitOrderNo");
            
            winitOrderNo = json.getString("winitOrderNo");
            allocationOrderNo = json.getString("allocationOrderNo");
            isByRecommandQty = json.getString("isByRecommandQty");
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }

        // 根据订单号查询入库包裹（A、A+）以及商品信息,将包裹按商品进行统计,并查出对应的库存等信息
        QueryInboundMerchandiseCommand command = new QueryInboundMerchandiseCommand();
        command.setCtx(CommandContext.getContext());
        command.setOrderNo(winitOrderNo);
        command.setIsByRecommandQty(isByRecommandQty);
        List<InboundMerchandiseDetailsVo> merchandises = inboundMerchandiseService.queryCrossDockMerListByOrderNo(command);
        
        if (StringUtils.isNotEmpty(allocationOrderNo) && !("Y".equals(isByRecommandQty))) {
            // 如果已经生成转存单，就去查询转存单下的商品
            QueryOrderMerchandiseByOrderNoCommand allocationMerCommand = new QueryOrderMerchandiseByOrderNoCommand();
            allocationMerCommand.setOrderNo(allocationOrderNo);
            List<AllocationOrderMerchandiseVo> merchandiseList = allocationOrderMerchandiseService.getMerchandiseList(allocationMerCommand);
            
            Map<String, AllocationOrderMerchandiseVo> merMap = new HashMap<String, AllocationOrderMerchandiseVo>();
            if (CollectionUtils.isNotEmpty(merchandiseList)) {
                for (AllocationOrderMerchandiseVo merVo : merchandiseList) {
                    merMap.put(merVo.getMerchandiseSerno(), merVo);
                }
                
                for (InboundMerchandiseDetailsVo vo : merchandises) {
                    String mCode = vo.getMerchandiseSerno();
                    AllocationOrderMerchandiseVo merVo = merMap.get(mCode);
                    if (merVo != null) {
                        vo.setInboundMerchandiseId(merVo.getId());
                        vo.setEstimateCrossDockQty(merVo.getEstimateDispatchQty());
                        vo.setPlanItemQty(merVo.getExpectQty());
                    }
                }
            }
        }
        responseMsg.setData(AllocationOrderMerchandiseBuilder.buildCrossMerList(merchandises));
        return SUCCESS;
    }

    /**
     * 查询商品的实际单品数
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/queryCrossDockActualItemQty")
    public String queryCrossDockActualItemQty(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        String orderNo = null;
        String mCode = null;
        Integer planItemQty = null;
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            ValidateUtil.validNotNull(json, "orderNo");
            ValidateUtil.validNotNull(json, "mCode");
            ValidateUtil.validNotNull(json, "planItemQty");
            orderNo = json.getString("orderNo");
            mCode = json.getString("mCode");
            planItemQty = json.getInteger("planItemQty");
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }

        // 据入库单以及商品条码、预计越库数计算实际越库数以及包裹数.
        QueryCrossDockActualItemQtyCommand command = new QueryCrossDockActualItemQtyCommand();
        command.setCtx(CommandContext.getContext());
        command.setOrderNo(orderNo);
        command.setMerchandiseSerno(mCode);
        command.setPlanItemQty(planItemQty);
        Map<String, Integer> result = inboundMerchandiseService.queryCrossDockActualItemQty(command);
        responseMsg.setData(result);
        return SUCCESS;
    }
}
